package com.fcy.teamwork.business.main.homepage

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.fcy.teamwork.base.BaseActivity
import com.fcy.teamwork.base.BaseFragment
import com.fcy.teamwork.business.chat.ChatAct
import com.fcy.teamwork.business.main.homepage.adapter.MessageListAdapter
import com.fcy.teamwork.business.main.homepage.viewmodel.MessageViewModel
import com.fcy.teamwork.databinding.HomepageMessageBinding

class MessageFrag : BaseFragment<HomepageMessageBinding>() {
    private val vm: MessageViewModel by activityViewModels()

    private val adapter = MessageListAdapter().apply {
        onItemClick = {
            modifyState(it.identify, false)
            (context as? BaseActivity<*>)?.apply {
                startActivity(Intent(this, ChatAct::class.java).apply {
                    putExtra("targetType", it.getBrand())
                    putExtra("targetId", it.identify)
                })
            }
        }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.actionBar.tvTitle.text = "消息"
        binding.rvMessages.also {
            it.adapter = adapter
            it.layoutManager = LinearLayoutManager(this.context)
        }
        lifecycleScope.launchWhenCreated {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                adapter.submitData(
                    vm.loadConversations()
                )
            }
        }
        lifecycleScope.launchWhenCreated {
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                vm.unReadFlow.collect {
                    adapter.modifyState(it)
                }
            }
        }
    }

    override fun initViewBinding(
        inflater: LayoutInflater?,
        container: ViewGroup?
    ) = HomepageMessageBinding.inflate(layoutInflater)

}